package cn.itcast.controller.company;

import cn.itcast.controller.BaseController;
import cn.itcast.domain.company.Company;
import cn.itcast.service.company.CompanyService;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/company")//一级路径
public class CompanyController extends BaseController {

    @Reference
    private CompanyService companyService;

   // @RequiresPermissions("企业管理") //使用此注解表示  如果要进入到此页面需要有企业管理权限
    @RequestMapping(value = "/list",name = "查询所有企业")
    public String findAll(@RequestParam(name = "page",defaultValue = "1") Integer pageNum,
                          @RequestParam(name = "pageSize",defaultValue = "10") Integer pageSize){
        //List<Company> companyList = companyService.findAll();
        //request.setAttribute("list",companyList);

        //使用PageHelper框架  写一个方法 参数 前端传过来的页数 和每一页显示条数  返回一个pageInfo
        PageInfo<Company> pageInfo = companyService.findByPage(pageNum, pageSize);
        request.setAttribute("page",pageInfo);
        //int i=1/0;
        return "company/company-list";
    }

    @RequestMapping(value = "/toAdd",name = "添加企业")
    public String save(Company company){

        //直接转发到企业添加页面
        return "company/company-add";
    }

    @RequestMapping(value = "/edit",name = "保存企业")
    public String edit(Company company){
        //判断传递过来的参数是否有id的值   没有就保存save   有更新update
        if (StringUtils.isEmpty(company.getId())) {
            String id = UUID.randomUUID().toString();
            company.setId(id);
            companyService.save(company);
        }else{
            companyService.update(company);
        }

        //直接重定向到企业添加页面
        return "redirect:/company/list.do";
    }


    @RequestMapping(value = "/toUpdate",name = "跳转到编辑页面（编辑和新增同一个页面）")
    public String toUpdate(String id){
        //数据回显
        Company company = companyService.findById(id);

        request.setAttribute("company",company);
        //直接转发到编辑页面
        return "company/company-add";
    }

    @RequestMapping(value = "/delete",name = "删除企业")
    public String delete(String id){

        companyService.deleteById(id);

        //直接转发到编辑页面
        return "redirect:/company/list.do";
    }
}
